define(function(require){
    $(function(){
    	/*---------- 组织管理——管理员 ----------*/
    	
    	/* 表格 */
    	var bodyTemplate = ['<tr org_id="{id}">',
	    	                    '<td class="txtc org_name"><a href="/trp/user/?org_id={id}" title="{name}">{name}</a></td>',
	    	                    '<td class="txtc org_contact">{contact}</td>',
	    	                    '<td class="txtc org_type">{type}</td>',
	    	                    '<td class="txtr org_balance" style="padding-right:20px;">{in_balance}</td>',
	    	                    '<td class="txtr org_balance" style="padding-right:20px;">{out_balance}</td>',
	    	                    '<td class="txtr org_balance" style="padding-right:20px;">{ally_balance}</td>',
	    	                    '<td class="txtl org_description">{description}</td>',
		                     	'<td class="txtc">',
		                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
		                     		'<a class="ibtn rechargebtn" href="javascript:;" title="充值"><span class="glyphicon glyphicon-usd"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');
        
        var $list = $('#organizationList'),
        	grid = Grid.init({
	            holder:'organizationList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/organization/get_organizations',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        //组织类型：0平台   2商铺   1供应商
        grid.modifyModel(function(data){
        	if(data.type==0){
        		data.type = '平台';
        	}else if(data.type==1){
        		data.type = '供应商';
        	}else{
        		data.type = '商铺';
        	}
        	if(data.in_balance=='-0.00')data.in_balance='0';
        	if(data.out_balance=='-0.00')data.out_balance='0';
        	if(data.ally_balance=='-0.00')data.ally_balance='0';
    	});
        grid.onfilled(function(data){
        	grid.data = data;
    		$('[name=charge_seq]').val(data.charge_seq);
    		$('.rechargebtn',$list).each(function(){
    			var $tr = $(this).parents('tr:first');
    			if($('.org_type',$tr).text()=='平台'){
    				$(this).removeClass('rechargebtn').addClass('disabled');
    			}
    		});
    		$('.ibtn').tooltip();
    	});
    	
        
        /* 数据搜索 */
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
        		orgtype = $('.pageheader select[name=orgtype]').val(),
            	pageSize = 20;
        	
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
            	org_type: orgtype,
        		search_text: txt,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        //按组织类型搜索
        $('.pageheader select[name=orgtype]').on('change', function(){
        	filterData();
        }).select2();
        
        /* 搜索 */
	    $('.pageheader .searchbox-btn').on('click', function(){
	    	filterData();
	    });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        
        /* 修改-dialog */
        $(document).on('click', '.editbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), org_id = $tr.attr('org_id');
        	var $dlg = $dialog({
                title: '修改组织信息',
                content: $('.pop-inofedit').clone().show()[0],
                width: '500px',
                onshow: function(){
                	var $node = $(this.node);
                	$('[name=name]',$node).val($('.org_name',$tr).text());
                	$('[name=contact]',$node).val($('.org_contact',$tr).text());
                	$('[name=type]',$node).val($('.org_type',$tr).text());
        			$('[name=description]',$node).val($('.org_description',$tr).text());
            	},
            	okValue: '确定',
            	ok: function(){
            		var $node = $(this.node);
            		$ajax.ajax({
            			url : '/trp/organization/do_modify/',
                		data: JSON.stringify({
                			org_id: org_id,
                			name: $('[name=name]',$node).val(),
                			contact: $('[name=contact]',$node).val(),
                			description: $('[name=description]',$node).val()
        				}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
	                    	$dialog.alert('修改组织信息成功！','success');
	                    	filterData(semi.utils.gridPage(grid));
                        },
                        error: function(){
                        	$dlg.close().remove();
	                    	$dialog.alert('修改组织信息失败，请稍后重试！','warning');
                        }
                	 });
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        });
        
        /* 充值-dialog */
        require('validate');
        $(document).on('click', '.rechargebtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), org_id = $tr.attr('org_id');
        	var $dlg = $dialog({
                title: '账户充值',
                content: $('.pop-recharge').clone().show()[0],
                width: '500px',
                okValue: '确定',
                ok: function(){
	            		var $node = $(this.node)
	        		$ajax.ajax({
	        			url : '/trp/organization/do_charge/',
	            		data: JSON.stringify({
	            			org_id: org_id,
	            			charge_seq: $('[name=charge_seq]').val(),
	            			in_balance: $('[name=in_balance]',$node).val(),
	            			out_balance: $('[name=out_balance]',$node).val(),
	            			ally_balance: $('[name=ally_balance]',$node).val()
	    				}),
	            		contentType : "application/json",
	                    type : 'POST',
	                    dataType : 'json',
	                    success: function(data){
	                    	$('[name=charge_seq]').val(data.charge_seq);
	                    	$dlg.close().remove();
	                    	$dialog.alert('账户充值成功！','success');
	                    	filterData(semi.utils.gridPage(grid));
	                    },
	                    error: function(data){
                    		$dlg.close().remove();
                    		$dialog.alert('账户充值失败，请稍后重试！','warning');
	                    }
	            	 });
	            	return false;
	            },
	            cancelValue: '取消',
	            cancel: true
            }).showModal();
        });
        
        /* 新增组织-dialog */
        $('.btn-create').on('click', function(){
        	var $dlg = $dialog({
                title: '新增组织',
                width: '500px',
            	onshow: function(){
            		var $d = this, $node = $($d.node);
            		$d.content($('.pop-createorg').clone().show()[0]);
            		$('[name=type]',$node).select2({
                    	ajax: {
                    		url: '/trp/organization/get_organization_types/',
                    		results: function(data){
                    			var resultArr = [];
                    			$.each(data.data, function(i,n){
                    				resultArr.push({id:n.id, text:n.name});
                    			});
                    			return {results: resultArr}
                    		}
                    	}
                    }).on('select2-open', function(){
						$(this).removeClass('error').siblings('label.error').remove();
					});
            	},
            	okValue: '确定',
            	ok: function(){
            		var $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		$ajax.ajax({
            			url : '/trp/organization/do_create/',
                		data: JSON.stringify({
                    		name: $('[name=name]',$node).val(),
                    		contact: $('[name=contact]',$node).val(),
                    		type: $('[name=type]',$node).val(),
                    		description: $('[name=description]',$node).val()
        				}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('新增组织成功！','success');
                        	filterData();
                        },
                        error: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('新增组织失败，请稍后重试！','warning');
                        }
                	 });
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        	
        });
        
    	
    });
});